package com.feicheng.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.feicheng.common.constant.Constant;
import com.feicheng.common.exception.SystemException;
import com.feicheng.common.message.StoreMessage;
import com.feicheng.common.result.ResultInfo;
import com.feicheng.common.wx.WxHTTPInterface;
import com.feicheng.common.wx.pay.WxPayBean;
import com.feicheng.persistence.entity.*;
import com.feicheng.persistence.model.AccessMain;
import com.feicheng.persistence.model.AccessRecordMain;
import com.feicheng.persistence.service.*;
import com.feicheng.service.BaseService;
import com.feicheng.service.IFStoreService;
import com.feicheng.wxpay.app.WxAppPayBean;

import lombok.experimental.Tolerate;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @see com.feicheng.service.IFStoreService
 */
@Slf4j
@Service
public class FStoreServiceImpl extends BaseService implements IFStoreService {

    @Resource(name="wx-http")
    WxHTTPInterface wxHTTPInterface;

    @Autowired
    IAccessService accessService;

    @Autowired
    IStoreAccessService storeAccessService;

    @Autowired
    IStoreService storeService;

    @Autowired
    IStoreWxService storeWxService;

    @Autowired
    IWxServerService iWxServerService;

    @Autowired
    IAccessRecordService accessRecordService;

    @Autowired
    StoreMessage storeMessage;

    @Autowired
    IStoreUserService iStoreUserService;

    @Autowired
    IStoreUserInfoService iStoreUserInfoService;

    @Autowired
    IStoreUserRoleService iStoreUserRoleService;

    @Resource(name="store-wx-pay")
    Map<String, WxPayBean> storeWxPayService;

    @Override
    public ResultInfo closeStore(Integer storeId) {
        storeWxPayService.remove(storeId.toString());

        Store storeAuto = new Store();
        storeAuto.setStoreId(storeId);
        storeAuto.setStatu(false);

        storeService.updateById(storeAuto);

        return ResultInfo.success();
    }

    @Override
    public ResultInfo openStore(Integer storeId) {

        /* 检查设备是否齐全 服务号  商户号 */
        QueryWrapper<StoreAccess> storeAccessQueryWrapper = new QueryWrapper<StoreAccess>();
        storeAccessQueryWrapper.eq(Constant.ENTITY.STORE_ACCESS.STORE_ID, storeId);

        List<StoreAccess> storeAccesses = storeAccessService.list(storeAccessQueryWrapper);
        Boolean in = false;
        Boolean out = false;
        for (StoreAccess storeAccess : storeAccesses) {
            Access access = accessService.getById(storeAccess.getAccessId());
            if (access.getStatu() && !access.getDFlg()) {
                if (storeAccess.getIoFlg()) {
                    in = true;
                } else {
                    out = true;
                }
            }
        }

        if (!(in && out)) {
            // TODO 门禁设备信息不完整，不能开店。
            throw new SystemException("门禁设备信息不完整，不能开店。");
        }

        /* 检查公众号是否齐全 服务号  商户号 */
        QueryWrapper<StoreWx> storeWxQueryWrapper = new QueryWrapper<StoreWx>();
        storeWxQueryWrapper.eq(Constant.ENTITY.STORE_WX.STORE_ID, storeId);
        List<StoreWx> storeWxes = storeWxService.list(storeWxQueryWrapper);

        if (2 > storeWxes.size()) {
            throw new SystemException("公众号信息不全面，不能开业！");
        }

        JSONArray wxIds = new JSONArray();
        for (StoreWx storeWx : storeWxes) {
            wxIds.add(storeWx.getWId());
        }

        QueryWrapper<WxServer> wxServerQueryWrapper = new QueryWrapper<WxServer>();
        wxServerQueryWrapper.in(Constant.ENTITY.WX_SERVER.W_ID, wxIds);
        wxServerQueryWrapper.eq(Constant.ENTITY.WX_SERVER.STATU, true);
        wxServerQueryWrapper.eq(Constant.ENTITY.WX_SERVER.D_FLG, false);
        List<WxServer> wxServers = iWxServerService.list(wxServerQueryWrapper);
        if (2 != wxServers.size()) {
            throw new SystemException("公众号信息不全面，不能开业！");
        }
        String appId = "";
        String secKey = "";
        String mchid = "";
        String merchantSerialNo = "";
        String merchantPrivateKeyStr = "";
        String apiV3Key = "";
        String certV2 = "";
        String privateKeyV2 = "";
        String apiV2Key = "";
        String payUrl = "";
        for (WxServer wxServer : wxServers) {
            if (Constant.VAL.WX_TYPE.P.equals(wxServer.getWxType())) {
                mchid = wxServer.getMerchantId();
                merchantSerialNo = wxServer.getMerchantSerialNo();
                merchantPrivateKeyStr = wxServer.getMerchantPrivateKeyStr();
                apiV3Key = wxServer.getApiV3Key();
                certV2 = wxServer.getCertV2();
                privateKeyV2 = wxServer.getPrivateKeyV2();
                apiV2Key = wxServer.getApiV2Key();
                payUrl = wxServer.getPayUrl();
            } else if (Constant.VAL.WX_TYPE.Y.equals(wxServer.getWxType())) {
                appId = wxServer.getAppId();
                secKey = wxServer.getAccessKey();
            }
        }

        if (!StringUtils.hasLength(appId)) {
            throw new SystemException("公众号信息不全面，不能开业: 服务号APPID缺失");
        }

        if (!StringUtils.hasLength(secKey)) {
            throw new SystemException("公众号信息不全面，不能开业: 服务号密钥缺失");
        }

        if (!StringUtils.hasLength(mchid)) {
            throw new SystemException("公众号信息不全面，不能开业: 商户号缺失");
        }

        if (!StringUtils.hasLength(merchantSerialNo)) {
            throw new SystemException("公众号信息不全面，不能开业: 商户号支付证书序列号V3版本缺失");
        }

        if (!StringUtils.hasLength(merchantPrivateKeyStr)) {
            throw new SystemException("公众号信息不全面，不能开业: 商户号支付证书私钥V3版本缺失");
        }

        if (!StringUtils.hasLength(apiV3Key)) {
            throw new SystemException("公众号信息不全面，不能开业: 商户号API秘钥V3版本缺失");
        }

//        if (!StringUtils.hasLength(apiV2Key)) {
//            throw new SystemException("公众号信息不全面，不能开业: 商户号API秘钥V2版本缺失");
//        }
//
//        if (!StringUtils.hasLength(certV2)) {
//            throw new SystemException("公众号信息不全面，不能开业: 商户号证书文件V2版缺失");
//        }

//        if (!StringUtils.hasLength(privateKeyV2)) {
//            throw new SystemException("公众号信息不全面，不能开业: 商户号私钥文件V2版缺失");
//        }

        if (!StringUtils.hasLength(payUrl)) {
            throw new SystemException("公众号信息不全面，不能开业: 商户号API支付目录缺失");
        }

//        storeWxPayService.put(storeId.toString(),
//                new WxPayBean(appId, secKey,
//                        mchid, merchantSerialNo,
//                        merchantPrivateKeyStr,
//                        apiV3Key,
//                        certV2,
//                        privateKeyV2,
//                        apiV2Key,
//                        payUrl,
//                        wxHTTPInterface));
        
        storeWxPayService.put(storeId.toString(),
                new WxAppPayBean(
                		appId, 
                		secKey,
                        mchid, 
                        merchantPrivateKeyStr,
                        merchantSerialNo,
                        apiV3Key,
                        payUrl));
        log.info("门店ID："+storeId+"开店成功；商户号："+mchid);
        Store storeAuto = new Store();
        storeAuto.setStoreId(storeId);
        storeAuto.setStatu(true);

        storeService.updateById(storeAuto);

        return ResultInfo.success();
    }

    @Override
    public ResultInfo getStoreWithAppId(String appId) {

        QueryWrapper<WxServer> wxServerQueryWrapper = new QueryWrapper<WxServer>();
        wxServerQueryWrapper.eq(Constant.ENTITY.WX_SERVER.APP_ID, appId);
        wxServerQueryWrapper.eq(Constant.ENTITY.WX_SERVER.WX_TYPE, Constant.VAL.WX_TYPE.Y);
        wxServerQueryWrapper.eq(Constant.ENTITY.WX_SERVER.STATU, true);
        wxServerQueryWrapper.eq(Constant.ENTITY.WX_SERVER.D_FLG, false);
        List<WxServer> wxServers = iWxServerService.list(wxServerQueryWrapper);
        if (1 != wxServers.size()) {
            throw new SystemException(storeMessage.getE01());
        }

        WxServer wxServer = wxServers.remove(0);

        QueryWrapper<StoreWx> storeWxQueryWrapper = new QueryWrapper<StoreWx>();
        storeWxQueryWrapper.eq(Constant.ENTITY.STORE_WX.W_ID, wxServer.getWId());
        List<StoreWx> storeWxes = storeWxService.list(storeWxQueryWrapper);

        if (1 != storeWxes.size()) {
            throw new SystemException(storeMessage.getE01());
        }

        Store store = storeService.getById(storeWxes.remove(0).getStoreId());

        return ResultInfo.success(store);
    }

    /**
     * 分页查询门店信息
     * @autor 葛仁旭
     * @param param 门店名称 联系人 电话 地址 状态 当前页 每页条数
     * @return
     */
    @Override
    public ResultInfo getStoresByPage(JSONObject param) {
        // 构建查询条件
        QueryWrapper<Store> storeQueryWrapper = new QueryWrapper<Store>();
        storeQueryWrapper.eq(Constant.ENTITY.STORE.D_FLG,0);
        //判断参数为空
        if(null == param) {
            //获得分页参数
            //默认第一页
            Integer current = 1;
            //默认一页十条
            Integer size = 10;
            //分页查询
            Page<Store> storePage = storeService.getStoresByPage(new Page<>(current,size),storeQueryWrapper);
            return ResultInfo.success(storePage);
        } else {
            //构建条件查询的条件对应对象
            Store selectStore = JSONObject.toJavaObject(param,Store.class);
            // 如果门店id不是空把id加入到查询的条件中
            if (null != selectStore.getStoreId()) {
                storeQueryWrapper.like(Constant.ENTITY.STORE.STORE_ID,selectStore.getStoreId());
            }
            // 如果店名不是空把店名加入到查询的条件中
            if (null != selectStore.getName()) {
                storeQueryWrapper.like(Constant.ENTITY.STORE.NAME,selectStore.getName());
            }
            // 如果地址不是空把地址加入到查询的条件中
            if (null != selectStore.getAddress()) {
                storeQueryWrapper.like(Constant.ENTITY.STORE.ADDRESS,selectStore.getAddress());
            }
            // 如果电话号码不是空把电话号码加入到查询的条件中
            if (null != selectStore.getConTel()) {
                storeQueryWrapper.like(Constant.ENTITY.STORE.CON_TEL,selectStore.getConTel());
            }
            // 如果联系人不是空把联系人加入到查询的条件中
            if (null != selectStore.getConPerson()) {
                storeQueryWrapper.like(Constant.ENTITY.STORE.CON_PERSON,selectStore.getConPerson());
            }
            // 如果状态不是空把状态加入到查询的条件中
            if (null != selectStore.getStatu()) {
                if (selectStore.getStatu()){
                    storeQueryWrapper.eq(Constant.ENTITY.STORE.STATU,true);

                }else {
                    storeQueryWrapper.eq(Constant.ENTITY.STORE.STATU,false);

                }
            }
            //获得分页参数
            Integer current = param.getInteger(Constant.HTTP.PARAM.CURRENT);
            Integer size = param.getInteger(Constant.HTTP.PARAM.SIZE);
            //判断当前页是否为空,为空则默认第一页
            if(null == current) {
                current = 1;
            }
            //判断条数是否为空，为空则默认一页十条
            if(null == size) {
                size = 10;
            }
            // 创建分页查询
            Page<Store> storePage = storeService.getStoresByPage(new Page<>(current,size),storeQueryWrapper);
            // 返回查询结果
            return ResultInfo.success(storePage);
        }
    }
    /**
     * 取得所有门店
     * @autor 葛仁旭
     * @param param
     * @return
     */
    @Override
    public ResultInfo getStores(JSONObject param) {
        /* 创建条件构造器，取得DFlg是0的所有门店信息*/
        QueryWrapper<Store> storeQueryWrapper = new QueryWrapper<>();
        storeQueryWrapper.eq(Constant.ENTITY.STORE.D_FLG,0);
        /*更新*/
        storeService.list(storeQueryWrapper);
        return ResultInfo.success(storeService.list(storeQueryWrapper));
    }

    /**
     * 删除门店信息
     * @autor 葛仁旭
     * @param storeId
     * @return
     */
    @Override
    public ResultInfo deleteStore(Integer storeId) {
        //确认门店id不为空
        if (null == storeId) {
            throw new SystemException("错误");
        }
        //创建门店对象，DFlg默认0
        Store store = new Store();
        store.setStoreId(storeId);
        store.setDFlg(true);
        //更新门店表
        storeService.updateById(store);
        return ResultInfo.success();
    }

    /**
     * 更新门店信息
     * @autor 葛仁旭
     * @param param
     * @return
     */
    @Override
    public ResultInfo updateStore(JSONObject param) {
        // 如果取得的参数为空 抛出异常
        if (null == param.toJavaObject(Store.class)) {
            //throw new SystemException("");
        }
        // String转对象
        Store store = param.toJavaObject(Store.class);
        // 根据storeId更改门店信息
        store.setDFlg(false);
        storeService.updateById(store);
        return ResultInfo.success(store);
    }


    /**
     * 取得门店信息
     * @autor 葛仁旭
     * @param storeId
     * @return 门店基本信息 门禁信息 公众号信息
     */
    @Override
    public ResultInfo getStoreInfo(Integer storeId) {
        /*从门店表里取得门店基本信息,
        从门店门禁中间表取得门禁ID，从门禁表里取得门禁基本信息，
        从门店和公众号中间表取得公众号ID，从公众号取得公众号基本信息*/

        //创建返回值MAP集合
        Map<String,List> storeMap = new HashMap<>();
        //创建条件构造器，根据dflg=0和门店Id 取门店信息
        QueryWrapper<Store> storeQueryWrapper = new QueryWrapper<Store>();
        storeQueryWrapper.eq(Constant.ENTITY.STORE.D_FLG,0);
        storeQueryWrapper.eq(Constant.ENTITY.STORE.STORE_ID,storeId);
        //根据门店ID在数据库取得门店详细信息
        List<Store> store = storeService.list(storeQueryWrapper);
        //返回的map集合存门店信息
        storeMap.put(Constant.ENTITY.STORE.TABLE,store);
        //创建条件构造器 根据门店id 取门禁和门店中间表信息
        QueryWrapper<StoreAccess> storeAccessQueryWrapper = new QueryWrapper<StoreAccess>();
        storeAccessQueryWrapper.eq(Constant.ENTITY.STORE_ACCESS.STORE_ID,storeId);
        //取得门店和门禁中间表信息
        List<StoreAccess> storeAccesses = storeAccessService.list(storeAccessQueryWrapper);
        //判断门店和门禁中间表数据是否为空，是否查询门禁信息
        if(storeAccesses.size() > 0){
            //创建条件构造器 循环取所有门禁id
            List<Integer> accessIds = new ArrayList<>();
            for ( int i = 0 ; i < storeAccesses.size() ; i++ ) {
                accessIds.add(storeAccesses.get(i).getAccessId());
            }
            //取得门禁对象集合
            List<Access> accesses = accessService.listByIds(accessIds);
            List<AccessMain> accessMains = new ArrayList<>();

            //循环添加所有门禁详细信息和门店门禁中间表中出入信息
            for ( int i = 0 ; i < accesses.size() ; i++ ) {
                AccessMain accessMain = new AccessMain();
                accessMain.setAccessId(accesses.get(i).getAccessId());
                accessMain.setModelNumber(accesses.get(i).getModelNumber());
                accessMain.setUId(accesses.get(i).getUId());
                accessMain.setUKey(accesses.get(i).getUKey());
                accessMain.setSn(accesses.get(i).getSn());
                accessMain.setStatu(accesses.get(i).getStatu());
                accessMain.setIoFlg(storeAccesses.get(i).getIoFlg());
                accessMains.add(accessMain);
            }

            //返回的map集合存门禁信息
            storeMap.put(Constant.ENTITY.ACCESS.TABLE,accessMains);
        }
        //创建条件构造器 根据门店id
        QueryWrapper<StoreWx> storeWxQueryWrapper = new QueryWrapper<StoreWx>();
        storeWxQueryWrapper.eq(Constant.ENTITY.STORE_WX.STORE_ID,storeId);
        //取得门店和公众号中间表信息
        List<StoreWx> storeWxes = storeWxService.list(storeWxQueryWrapper);
        //判断门店和公众号中间表数据是否为空，是否查询公众号信息
        if(storeWxes.size() > 0){
            //创建条件构造器 循环取所有公众号信息
            QueryWrapper<WxServer> wxServerQueryWrapper = new QueryWrapper<WxServer>();
            wxServerQueryWrapper.eq(Constant.ENTITY.WX_SERVER.D_FLG,0);
            for ( int i = 0 ; i < storeWxes.size() ; i++ ) {
                wxServerQueryWrapper.eq(Constant.ENTITY.WX_SERVER.W_ID,storeWxes.get(i).getWId()).or();
            }
            //取得公众号对象集合
            List<WxServer> wxServers = iWxServerService.list(wxServerQueryWrapper);
            for ( int i = 0 ; i < wxServers.size() ; i++ ) {
                wxServers.get(i).setAccessKey("******");
                wxServers.get(i).setApiV3Key("******");
                wxServers.get(i).setMerchantPrivateKeyStr("******");
            }
            //返回的map集合存公众号信息
            storeMap.put(Constant.ENTITY.WX_SERVER.TABLE,wxServers);
        }
        //返回根据门店ID取得的门店信息，所有门禁和公众号信息
        
        // TODO lizhi 取得门店用户信息
        //创建storeUserInfoQueryWrapper
        QueryWrapper<StoreUserInfo> storeUserInfoQueryWrapper = new QueryWrapper<>();
        //根据门店id查询userId
        storeUserInfoQueryWrapper.eq(Constant.ENTITY.STORE_USER_INFO.STORE_ID,storeId);
        List<StoreUserInfo> storeUserInfoList = iStoreUserInfoService.list(storeUserInfoQueryWrapper);
        List<StoreUser> storeUsers = new ArrayList<>();
        for (int index = 0; index < storeUserInfoList.size(); index++) {
            StoreUser storeUser = iStoreUserService.getById(storeUserInfoList.get(index).getUserId());
            storeUsers.add(storeUser);
        }
        storeMap.put(Constant.ENTITY.STORE_USER.TABLE,storeUsers);
        return ResultInfo.success(storeMap);
    }


    /**
     * 新增门店信息
     * @autor 葛仁旭
     * @param param
     * @return
     */
    @Transactional
    @Override
    public ResultInfo newStore(JSONObject param) {
        // 如果取得的参数为空 抛出异常
       /* if (null == param.toJavaObject(Store.class)) {
            //throw new SystemException("");
        }*/
        //String转对象
        Store store = param.toJavaObject(Store.class);
        StoreUser storeUser = param.toJavaObject(StoreUser.class);
        store.setStatu(false);
        store.setDFlg(false);
        QueryWrapper<StoreUser> storeUserQueryWrapper = new QueryWrapper<>();
        storeUserQueryWrapper.eq(Constant.ENTITY.STORE_USER.ACCOUNT,storeUser.getAccount());
        List<StoreUser> storeUsers = iStoreUserService.list(storeUserQueryWrapper);
        if (storeUsers != null && storeUsers.size() > 0){
            throw new SystemException("账号已存在");
        }
        //新增门店
        storeService.save(store);
        storeUser.setCu(0);
        storeUser.setUu(0);
        //新增store_user
        iStoreUserService.save(storeUser);
        //创建并初始化 StoreUserInfo
        StoreUserInfo storeUserInfo = new StoreUserInfo();
        storeUserInfo.setUserId(storeUser.getUserId());
        storeUserInfo.setStoreId(store.getStoreId());
        //新增store_user_info
        iStoreUserInfoService.save(storeUserInfo);
        //创建并初始化  StoreUserRole
        StoreUserRole storeUserRole = new StoreUserRole();
        storeUserRole.setRoleId(1);
        storeUserRole.setUserId(storeUser.getUserId());
        // 新增store_user_role
        iStoreUserRoleService.save(storeUserRole);
        return ResultInfo.success();
    }



    /**
     * 新增门店公众号信息
     * @autor 姜浩男
     * @param wxServer
     * @param storeId
     * @return
     */
    @Override
    public ResultInfo newWxServer(WxServer wxServer, Integer storeId) {
        iWxServerService.save(wxServer);
        //构建storeWx对象
        StoreWx storeWx = new StoreWx();
        storeWx.setStoreId(storeId);
        storeWx.setWId(wxServer.getWId());
        storeWxService.save(storeWx);
        return ResultInfo.success();
    }

    @Override
    public ResultInfo getWxServer(Integer wId) {
        if (null == wId){
            throw new SystemException("");
        }
        QueryWrapper<WxServer> wxServerQueryWrapper = new QueryWrapper<WxServer>();
        wxServerQueryWrapper.eq(Constant.ENTITY.WX_SERVER.W_ID,wId);

        return ResultInfo.success(iWxServerService.getOne(wxServerQueryWrapper));
    }

    /**
     * 更新门店公众号信息
     * @autor 姜浩男
     * @param wxServer
     * @param wxServer
     * @return
     */
    @Override
    public ResultInfo updateWxServer(WxServer wxServer) {
        if(null == wxServer.getWId() || wxServer.getWId() == 0) {
            //主键为空
            throw new SystemException("");
        }
        if(null == wxServer.getWxType()) {
            //请选择公众号类型
            throw new SystemException("");
        }
        if(null == wxServer.getAppId()) {
            //请输入公众号APPID
            throw new SystemException("");
        }
        if(null == wxServer.getAccessKey()) {
            //微信公众号的密钥
            throw new SystemException("");
        }
        if(null == wxServer.getMerchantId()) {
            //微信公众号的商户号
            throw new SystemException("");
        }
        if(null == wxServer.getMerchantSerialNo()) {
            //微信公众号的商户证书序列号
            throw new SystemException("");
        }
        if(null == wxServer.getMerchantPrivateKeyStr()) {
            //微信公众号的私钥字符串
            throw new SystemException("");
        }
        if(null == wxServer.getApiV3Key()) {
            //微信公众号的V3秘钥
            throw new SystemException("");
        }
        if(null == wxServer.getPayUrl()) {
            //微信公众号的地址
            throw new SystemException("");
        }
        return ResultInfo.success(iWxServerService.updateById(wxServer));
    }
    /**
     * 删除门店公众号信息
     * @autor 姜浩男
     * @param
     * @param wId
     * @return
     */
    @Override
    public ResultInfo deleteWxServer(Integer wId) {
        //判断id是否缺失
        if(null == wId){
            throw new SystemException("");
        }
        //构建公众号实体类对象
        WxServer wxServer = new WxServer();
        wxServer.setWId(wId);
        wxServer.setDFlg(true);
        //更新公众号表
        iWxServerService.updateById(wxServer);
        QueryWrapper<StoreWx> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(Constant.ENTITY.STORE_WX.W_ID, wId);
        storeWxService.remove(queryWrapper);
        return ResultInfo.success();
    }

    /**
     * 分页查询门禁信息
     * @autor 邱明昶
     * @param param 门禁设备ID 序列号 授权key 出入 状态 门店编号 型号 当前页 每页条数
     * @return
     */
    @Override
    public ResultInfo getAccessesByPage(JSONObject param) {
        //构建未被删除条件构造器
        QueryWrapper<AccessMain> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(Constant.ENTITY.ACCESS.D_FLG, 0);
        //判断参数为空
        if(null == param) {
            //获得分页参数
            //默认第一页
            int current = 1;
            //默认一页十条
            int size = 10;
            //分页查询
            Page<AccessMain> result = accessService.getAccessesByPage(new Page<AccessMain>(current, size), queryWrapper);
            return ResultInfo.success(result);
        } else {
            //构建条件查询的条件对应对象
            Access selectAccess = JSONObject.toJavaObject(param, Access.class);
            StoreAccess selectStoreAccess = JSONObject.toJavaObject(param, StoreAccess.class);
            //若门禁设备ID不为空则加入条件构造器
            if (null != selectAccess.getAccessId()) {
                queryWrapper.eq(Constant.ENTITY.ACCESS.ACCESS_ID, selectAccess.getAccessId());
            }
            //若序列号不为空则加入条件构造器
            if (null != selectAccess.getSn()) {
                queryWrapper.like(Constant.ENTITY.ACCESS.SN, selectAccess.getSn());
            }
            //若授权key不为空则加入条件构造器
            if (null != selectAccess.getUKey()) {
                queryWrapper.like(Constant.ENTITY.ACCESS.U_KEY, selectAccess.getUKey());
            }
            //若设备id不为空则加入条件构造器
            if (null != selectAccess.getUId()) {
                queryWrapper.like(Constant.ENTITY.ACCESS.U_ID, selectAccess.getUId());
            }
            //若出入不为空则加入条件构造器
            if (null != selectStoreAccess.getIoFlg()) {
                queryWrapper.eq(Constant.ENTITY.STORE_ACCESS.IO_FLG, selectStoreAccess.getIoFlg());
            }
            //若状态不为空则加入条件构造器
            if (null != selectAccess.getStatu()) {
                queryWrapper.eq(Constant.ENTITY.ACCESS.STATU, selectAccess.getStatu());
            }
            //若门店编号不为空则加入条件构造器
            if (null != selectStoreAccess.getStoreId()) {
                queryWrapper.eq(Constant.ENTITY.STORE_ACCESS.STORE_ID, selectStoreAccess.getStoreId());
            }
            //若型号不为空则加入条件构造器
            if (null != selectAccess.getModelNumber()) {
                queryWrapper.like(Constant.ENTITY.ACCESS.MODEL_NUMBER, selectAccess.getModelNumber());
            }
            //获得分页参数
            Integer current = param.getInteger(Constant.HTTP.PARAM.CURRENT);
            Integer size = param.getInteger(Constant.HTTP.PARAM.SIZE);
            //判断当前页是否为空,默认第一页
            if(null == current || 0 >= current) {
                current = 1;
            }
            //判断条数是否为空，默认一页十条
            if(null == size || 0 >= size) {
                size = 10;
            }
            //分页查询
            Page<AccessMain> result = accessService.getAccessesByPage(new Page<>(current, size), queryWrapper);
            return ResultInfo.success(result);
        }
    }
    /**
     * 取得门禁信息
     * @autor 邱明昶
     * @param accessId
     * @return
     */
    @Override
    public ResultInfo getAccess(Integer accessId) {
        //判断门禁ID缺失
        if(null == accessId) {
            // TODO 门禁ID缺失
            throw new SystemException("");
        }
        //构造条件,根据id
        QueryWrapper<AccessMain> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(Constant.ENTITY.ACCESS.ACCESS_ID,accessId);
        //添加未被删除条件
        queryWrapper.eq(Constant.ENTITY.ACCESS.D_FLG, 0);
        //调用分页查询方法
        Page<AccessMain> result = accessService.getAccessesByPage(new Page<AccessMain>(1, 1), queryWrapper);
        //取得数据
        return ResultInfo.success(result.getRecords().get(0));
    }
    /**
     * 修改门禁信息
     * @autor 邱明昶
     * @param access 门禁基本信息
     * @param storeId 门店编号
     * @param ioFlg 出入
     * @return
     */
    @Override
    public ResultInfo updateAccess(Access access, Integer storeId, Boolean ioFlg) {
        //判断门禁信息缺失
        if(null == access){
            // TODO 门禁信息缺失
            throw new SystemException("");
        } else if (null == access.getAccessId() || null == access.getModelNumber() || null == access.getUId() || null == access.getUKey() || null == access.getSn() || null == access.getStatu()) {
            // TODO 门禁信息缺失
            throw new SystemException("");
        }
        //判断门店ID缺失
        if(null == storeId) {
            // TODO 门店ID缺失
            throw new SystemException("");
        }
        //更新门禁表
        accessService.updateById(access);
        //构建门禁-门店中间表实体类对象
        StoreAccess storeAccess=new StoreAccess();
        storeAccess.setAccessId(access.getAccessId());
        storeAccess.setStoreId(storeId);
        storeAccess.setIoFlg(ioFlg);
        //构建条件，根据门禁id
        QueryWrapper<StoreAccess> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq(Constant.ENTITY.STORE_ACCESS.ACCESS_ID,access.getAccessId());

        //更新门禁-门店中间表
        storeAccessService.update(storeAccess,queryWrapper);
        return ResultInfo.success();
    }
    /**
     * 删除门禁信息
     * @autor 邱明昶
     * @param accessId 主键门禁编号
     * @return
     */
    @Override
    public ResultInfo deleteAccess(Integer accessId) {
        //判断id缺失
        if(null==accessId){
            // TODO 门禁ID缺失
            throw new SystemException("");
        }
        //构建门禁表实体类对象，设置门禁id，DFlg为1
        Access access = new Access();
        access.setAccessId(accessId);
        access.setDFlg(true);
        //更新门禁表
        accessService.updateById(access);
        QueryWrapper<StoreAccess> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(Constant.ENTITY.STORE_ACCESS.ACCESS_ID, accessId);
        storeAccessService.remove(queryWrapper);
        return ResultInfo.success();
    }
    /**
     * 新增门禁信息
     * @autor 邱明昶
     * @param access
     * @param storeId
     * @param ioFlg 出入
     * @return
     */
    @Tolerate
    @Override
    public ResultInfo newAccess(Access access, Integer storeId, Boolean ioFlg) {
        //判断门禁信息缺失
        if(null == access){
            // TODO 门禁信息缺失
            throw new SystemException("");
        } else if (null == access.getModelNumber() || null == access.getUId() || null == access.getUKey() || null == access.getSn() ) {
            // TODO 门禁信息缺失
            throw new SystemException("");
        }
        //判断门店ID缺失
        if(null == storeId) {
            // TODO 门店ID缺失
            throw new SystemException("");
        }
        //判断出入
        if(null == ioFlg) {
            // TODO 出入信息缺失
            throw new SystemException("");
        }
        //校验是否在该门店下有相同设备id的设备
        QueryWrapper<StoreAccess> storeAccessQueryWrapper = new QueryWrapper<>();
        storeAccessQueryWrapper.eq(Constant.ENTITY.STORE_ACCESS.STORE_ID,storeId);
        List<StoreAccess> storeAccesses = storeAccessService.list(storeAccessQueryWrapper);
        for (int index = 0; index < storeAccesses.size(); index++) {
            Access newAccess = accessService.getById(storeAccesses.get(index).getAccessId());
            if (newAccess.getUId().equals(access.getUId())){
                throw new SystemException("在该门店下，该设备型号已存在");
            }
        }
        //更新门禁表
        accessService.save(access);
        //构建门禁-门店中间表实体类对象
        StoreAccess storeAccess = new StoreAccess();
        storeAccess.setAccessId(access.getAccessId());
        storeAccess.setStoreId(storeId);
        storeAccess.setIoFlg(ioFlg);
        //更新门禁-门店中间表
        storeAccessService.save(storeAccess);
        return ResultInfo.success();
    }

    @Override
    public ResultInfo getAccessRecordByPage(AccessRecordMain accessRecordMain, Integer current, Integer size) {
        QueryWrapper<AccessRecordMain> queryWrapper = new QueryWrapper<AccessRecordMain>();
        //根据客户姓名查询
        if (StringUtils.hasLength(accessRecordMain.getClientName())) {
            queryWrapper.like(Constant.ENTITY.CLIENT.CLIENT_NAME, accessRecordMain.getClientName());
        }

        //根据客户电话查询
        if (StringUtils.hasLength(accessRecordMain.getPhone())) {
            queryWrapper.like(Constant.ENTITY.CLIENT.PHONE, accessRecordMain.getPhone());
        }

        //根据设备id查询
        if (StringUtils.hasLength(accessRecordMain.getUId()) ) {
            queryWrapper.like(Constant.ENTITY.ACCESS.U_ID, accessRecordMain.getUId());
        }
        //根据门店id查询
        if (null != accessRecordMain.getStoreId()) {
            queryWrapper.eq(Constant.ENTITY.STORE.STORE_ID, accessRecordMain.getStoreId());
        }

        //根据开始结束时间区间进行查询
        if (null != accessRecordMain.getSt()) {
            queryWrapper.ge(Constant.ENTITY.ACCESS_RECORD.CT, accessRecordMain.getSt());
        }

        if (null != accessRecordMain.getEd()) {
            queryWrapper.le(Constant.ENTITY.ACCESS_RECORD.CT, accessRecordMain.getEd());
        }

        //根据进出门进行查询
        if (null != accessRecordMain.getIoFlg()) {
            queryWrapper.eq(Constant.ENTITY.STORE_ACCESS.IO_FLG, accessRecordMain.getIoFlg());
        }

        queryWrapper.orderByDesc(Constant.ENTITY.ACCESS_RECORD.CT);

        Page<AccessRecordMain> result =
                accessRecordService.getAccessRecordByPage(
                        new Page<AccessRecordMain>(current, size), queryWrapper);

        return ResultInfo.success(result);
    }

    @Override
    public ResultInfo newAccessRecord(AccessRecord accessRecord) {
        if (null == accessRecord.getAccessId()){
            // TODO: 2021/12/29 二维码对象问题
            throw new SystemException("11");
        }
        if (null == accessRecord.getStoreId()){
            // TODO: 2021/12/29 二维码对象问题
            throw new SystemException("22");
        }
        if (null == accessRecord.getClientId()){
            // TODO: 2021/12/29 二维码对象问题
            throw new SystemException("33");
        }
        if (null == accessRecord.getCt()){
            // TODO: 2021/12/29 二维码对象问题
            throw new SystemException("44");
        }
        Integer id = accessRecord.getAccessId();
        return ResultInfo.success(accessRecordService.save(accessRecord));
    }


    /**
     * 分页查询扫码记录
     * @autor 姜浩男
     * @see com.feicheng.service.IFStoreService# getAccessRecordByPage(String clientName, LocalDateTime st, LocalDateTime ed, Integer storeId, String storeName, Integer accessId, Boolean ioFlg, Integer current, Integer size)
     * @return
     */
//    @Override
//    public ResultInfo getAccessRecordByPage(String clientName, LocalDateTime st,
//                                            LocalDateTime ed, Integer storeId,
//                                            String name, Integer accessId, Boolean ioFlg, Integer current, Integer size) {
//
//        QueryWrapper<AccessRecordMain> queryWrapper = new QueryWrapper<AccessRecordMain>();
//        //根据客户姓名查询
//        if (StringUtils.hasLength(clientName)) {
//            queryWrapper.like(Constant.ENTITY.CLIENT.CLIENT_NAME,clientName);
//        }
//
//        //根据设备id查询
//        if (null != accessId ) {
//            queryWrapper.eq(Constant.ENTITY.STORE_ACCESS.ACCESS_ID, accessId);
//        }
//        //根据门店id查询
////        if (null != storeId ) {
////            queryWrapper.eq(Constant.ENTITY.STORE.STORE_ID,storeId);
////        }
//        //根据门店名称查询
//        if (StringUtils.hasLength(name)) {
//            queryWrapper.like(Constant.ENTITY.STORE.NAME,name);
//        }
//        //根据开始结束时间区间进行查询
//        if (null != st  & null != ed ) {
//            queryWrapper.between(Constant.ENTITY.ACCESS_RECORD.CT,st,ed);
//        }
//        //根据进出门进行查询
//        if (null != ioFlg) {
//            queryWrapper.eq(Constant.ENTITY.STORE_ACCESS.IO_FLG,ioFlg);
//        }
//        if (null == current || 0 >= current){
//            current = 1;
//        }
//        if (null == size || 0 >= size){
//            size = 3;
//        }
////        accessRecordService.getById(accessId).getCt();
//        Page<AccessRecordMain> result = accessRecordService.getAccessRecordByPage(new Page<AccessRecordMain>(current,size), queryWrapper);
//        return ResultInfo.success(result);
//    }


}